import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    cart: [
      // 初始化购物车为空数组
    ]
  },
  getters: {
    cartItems: state => state.cart,
    totalAmount: state => state.cart.reduce((total, item) => total + item.price * item.quantity, 0)
  },
  mutations: {
    ADD_TO_CART(state, item) {
      let found = false;
      state.cart.forEach((cartItem, index) => {
        if (cartItem.id === item.id) {
          state.cart[index].quantity += item.quantity;
          found = true;
        }
      });
      if (!found) {
        state.cart.push({ ...item, quantity: 1 });
      }
    },
    REMOVE_FROM_CART(state, itemId) {
      state.cart = state.cart.filter(item => item.id !== itemId);
    },
    INCREMENT_QUANTITY(state, itemId) {
      state.cart.forEach(item => {
        if (item.id === itemId) {
          item.quantity++;
        }
      });
    },
    DECREMENT_QUANTITY(state, itemId) {
      state.cart.forEach(item => {
        if (item.id === itemId) {
          if (item.quantity > 1) item.quantity--;
        }
      });
    }
  },
  actions: {
    addToCart({ commit }, item) {
      commit('ADD_TO_CART', item);
    },
    removeFromCart({ commit }, itemId) {
      commit('REMOVE_FROM_CART', itemId);
    },
    incrementQuantity({ commit }, itemId) {
      commit('INCREMENT_QUANTITY', itemId);
    },
    decrementQuantity({ commit }, itemId) {
      commit('DECREMENT_QUANTITY', itemId);
    }
  }
});